//
//  MNDTransactionRecordViewController.m
//  minidai
//
//  Created by Steven.Yung on 2017/5/17.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDTransactionRecordViewController.h"
#import "MNDTransactionRecordCell.h"
#import "SYRefreshControl.h"
#import "MNDTransactionRecordHeaderView.h"
#import "MNDMonthlyTransactionViewController.h"
#import "MNDTransactionFilterViewController.h"
#import "NSDate+JKExtension.h"

/*! 筛选字段交易类型 1充值2提现3投资4回款5还款
 *  6体验金7奖励8红包12提现取消13提现失败
 *  15债权转出16借款17手续费 
 *  为空时 全部数据 这里用0 */
typedef NS_ENUM(NSInteger, TransactionType) {
    TransactionTypeAll      = 0,
    TransactionTypeRecharge = 1,
    TransactionTypeWithdraw = 2,
    TransactionTypeTender   = 3,
    TransactionTypeReturn   = 4,
    TransactionTypeRefund   = 5,
    TransactionTypeExper    = 6,
    TransactionTypeReward   = 7,
    TransactionTypeRepack   = 8,
    TransactionTypeWithdrawCancel = 12,
    TransactionTypeWithdrawFail   = 13,
    TransactionTypeTransfer       = 15,
    TransactionTypeBorrow         = 16,
    TransactionTypeHandling       = 17
};

@interface MNDTransactionRecordViewController () <UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

/*! 转换成模型后的数组 */
@property (strong, nonatomic) NSMutableArray *transactionList;
/*! 转换成模型前的原始数组 */
@property (strong, nonatomic) NSMutableArray *originalList;

@property (nonatomic) NSInteger perpage;
@property (nonatomic) NSInteger pagesize;
/*! 
 *  筛选字段交易类型1充值2提现3投资4回款5还款6体验金
 *  7奖励8红包12提现取消13提现失败15债权转出16借款17手续费 
 *  为空时 全部数据  
 */
@property (nonatomic) NSInteger type;

@property (weak, nonatomic) MNDTransactionFilterViewController *filterVC;

@end

@implementation MNDTransactionRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.perpage = 1;
    self.pagesize = 15;
    self.type = TransactionTypeAll; //默认全部，为0时不传值
    
    WeakSelf(self);
    
    [SYRefreshControl configGifMJRefresh:self.tableView
                                refreshType:MJRefreshSupportALl
                               beginRefresh:NO
                            timeLabelHidden:YES
                           stateLabelHidden:YES
                               refreshBlock:^{
        
        [weakself refreshRecordDatas];
    } loadMoreBlock:^{
        
        [weakself loadMoreRecordDatas];
    }];
    
    [self refreshRecordDatas];
    
    [self configFilterButton];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)configFilterButton {
    UIImage *itemImage = [UIImage imageNamed:@"finance_invest_btn-1"];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage: itemImage style:UIBarButtonItemStylePlain target:self action:@selector(filterAction:)];
    [item setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    
    if (@available(iOS 11.0, *)) {
        self.navigationItem.rightBarButtonItem = item;
    } else {
        self.navigationItem.rightBarButtonItems = @[spaceItem, item];
    }
}

- (void)filterAction:(id)sender {
    
    if (self.filterVC) {
        return;
    }
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Transaction" bundle:nil];
    
    MNDTransactionFilterViewController *filterVC = [storyboard instantiateViewControllerWithIdentifier:[MNDTransactionFilterViewController description]];
    
    [self.view addSubview:filterVC.view];
    [self addChildViewController:filterVC];
    filterVC.selectedIndex = self.type;
    self.filterVC = filterVC;
    
    WeakSelf(self);
    filterVC.filterDidSelectedBlock = ^(NSInteger index) {
        if (weakself.type != (index % 100)) {
            weakself.type = index % 100;
            [weakself.transactionList removeAllObjects];
            [weakself refreshRecordDatas];
        }
    };
}

- (void)refreshRecordDatas {
    
    WeakSelf(self);
    
    self.perpage = 1;
    NSMutableDictionary *preParam = [NSMutableDictionary dictionaryWithDictionary:@{@"perpage": @(_perpage), @"pagesize": @(_pagesize)}];
    if (self.type) {
        [preParam setObject:@(self.type) forKey:@"type"];
    }
    if (self.transactionList.count <= 0) {
        [self.view beginLoading];
    }
    
    [APIManager sendRequestWithPath:API_USER_TRANSACTION_LIST parameters:[MNDSign signedParamWithDict:preParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            NSArray *arr = responseModel.data[@"transaction_list"];
            
            [weakself.originalList removeAllObjects];
            [weakself.originalList addObjectsFromArray:arr];
            
            [weakself configDatas:weakself.originalList isRefresh:YES];
            [weakself.view configBlankPage:SYBlankPageTypeNoData hasData:arr.count reloadButtonBlock:nil];
        } else {
            if (weakself.transactionList.count <= 0) {
                [weakself.view configBlankPage:SYBlankPageTypeError hasData:NO reloadButtonBlock:^(id sender) {
                    [weakself refreshRecordDatas];
                }];
                return;
            }
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
                
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败"];
            }
        }
        
        [SYRefreshControl configAfterLoading:weakself.tableView hasData:weakself.transactionList.count];
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
        [SYRefreshControl configAfterLoading:weakself.tableView hasData:weakself.transactionList.count];
        if (weakself.transactionList.count <= 0) {
            SYBlankPageType blankType = [weakself.view blankPageTypeWithError:error];
            [weakself.view configBlankPage:blankType hasData:NO reloadButtonBlock:^(id sender) {
                [weakself refreshRecordDatas];
            }];
        }
    }];
}

- (void)loadMoreRecordDatas {
    WeakSelf(self);
    
    self.perpage ++;
    NSMutableDictionary *preParam = [NSMutableDictionary dictionaryWithDictionary:@{@"perpage": @(_perpage), @"pagesize": @(_pagesize)}];
    if (self.type) {
        [preParam setObject:@(self.type) forKey:@"type"];
    }
    
    [APIManager sendRequestWithPath:API_USER_TRANSACTION_LIST parameters:[MNDSign signedParamWithDict:preParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            
            NSArray *arr = responseModel.data[@"transaction_list"];
            
            [weakself.originalList addObjectsFromArray:arr];
            
            [weakself configDatas:weakself.originalList isRefresh:NO];
            [SYRefreshControl configAfterLoading:weakself.tableView hasData:arr.count];
            
        } else {
            [SYRefreshControl configAfterLoading:weakself.tableView hasData:weakself.transactionList.count];
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
                
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
        [SYRefreshControl configAfterLoading:weakself.tableView hasData:weakself.transactionList.count];
    }];
}

- (void)configDatas:(NSArray *)arr isRefresh: (BOOL)refresh {
    
    NSArray *returnArr = [MNDTransactionRecordModel mj_objectArrayWithKeyValuesArray:arr];
   
    NSMutableSet *set = [NSMutableSet set];
    
    [returnArr enumerateObjectsUsingBlock:^(MNDTransactionRecordModel *model, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *dateStr = [[NSDate jk_dateWithString:model.transaction_time format:@"yyyy-MM-dd HH:mm:ss"] jk_stringWithFormat:@"yyyy-MM"];
        [set addObject:dateStr];
        
    }];

    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO];
    NSArray *sortArr =  [set sortedArrayUsingDescriptors:@[sortDescriptor]];
    
    //接下来需要用到NSPredicate语法进行筛选
    __block NSMutableArray *groupArr = [NSMutableArray array];

    [sortArr enumerateObjectsUsingBlock:^(NSString *time, NSUInteger idx, BOOL * _Nonnull stop) {
     
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"transaction_time contains[c] %@", time];
        NSArray *tempArr = [NSArray arrayWithArray:[returnArr filteredArrayUsingPredicate:predicate]];
        NSDictionary *dict = @{@"date": time, @"rows": tempArr};
        [groupArr addObject:dict];

    }];
    if (refresh) {
        [self.transactionList removeAllObjects];
    }
    
    self.transactionList = [groupArr mutableCopy];
//    NSLog(@"set: %@", self.transactionList);
    [self.tableView reloadData];
}

#pragma mark - UITableView Datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.transactionList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSDictionary *dict = self.transactionList[section];
    NSArray *rows = dict[@"rows"];
    return rows.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 35.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    static NSString *const headerIdentifier = @"header";
    MNDTransactionRecordHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier: headerIdentifier];
    
    if (!headerView) {
        headerView = [[MNDTransactionRecordHeaderView alloc] initWithReuseIdentifier:headerIdentifier];
    }
    NSDictionary *dict = self.transactionList[section];
    NSDate *date = [NSDate jk_dateWithString:dict[@"date"] format:@"yyyy-MM"];
    NSDate *today = [NSDate date];
    if (date.jk_month == today.jk_month) {
        headerView.monthLabel.text = [NSString stringWithFormat:@"%ld年本月", (unsigned long)today.jk_year];
    } else {
        headerView.monthLabel.text = [date jk_stringWithFormat:@"yyyy年MM月"];
    }
    
//    WeakSelf(self);
    headerView.headerDidClickBlock = ^{
//        [weakself goMonthlyTransaction:date];
    };
    return headerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellIdentifier = @"cell";
    MNDTransactionRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    
    NSDictionary *dict = self.transactionList[indexPath.section];
    NSArray *rows = dict[@"rows"];
    cell.model = rows[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


- (void)goMonthlyTransaction:(NSDate *)selectDate {
    NSLog(@"selected date: %@", selectDate);
    [self performSegueWithIdentifier:[MNDMonthlyTransactionViewController description] sender:selectDate];
}



#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    if ([segue.identifier isEqualToString:[MNDMonthlyTransactionViewController description]]) {
        MNDMonthlyTransactionViewController *monthlyVC = segue.destinationViewController;
        monthlyVC.chooseDate = sender;
    }
}


- (NSMutableArray *)transactionList {
    if (!_transactionList) {
        _transactionList = [NSMutableArray array];
    }
    
    return _transactionList;
}

- (NSMutableArray *)originalList {
    if (!_originalList) {
        _originalList = [NSMutableArray array];
    }
    
    return _originalList;
}

@end
